﻿using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace PingWebsite
{
    class Program
    {
        static void Main(string[] args)
        {
            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                var browser = HttpWebRequest.Create(options.Url);
                var started = DateTime.Now;
                try
                {
                    Console.WriteLine(string.Format("Loading {0}...", options.Url));
                    var response = browser.GetResponse();
                    using (var sr = new StreamReader(response.GetResponseStream()))
                        Console.Write(sr.ReadToEnd());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    if (ex.InnerException != null)
                        Console.WriteLine(ex.InnerException.Message);
                    Process.Start(options.Url);
                }
                var now = DateTime.Now;
                var duration = now - started;
                Console.WriteLine(" // completed in " + duration.ToString(@"%m\:ss\.%FFF"));

            }
        }

        public class Options
        {
            [Option('u', "url", HelpText = "Specify the url to ping", Required = true)]
            public string Url { get; set; }

            [HelpOption]
            public string GetUsage()
            {
                var help = new HelpText
                {
                    Heading = new HeadingInfo("PingWebsite", "0.1"),
                    Copyright = new CopyrightInfo("DotNetWise", 2013),
                    AdditionalNewLineAfterOption = true,
                    AddDashesToOption = true
                };
                help.AddPreOptionsLine("Navigates to the given website and if it doesn't return HTTP 200 success error will open the url in your default website");
                help.AddPreOptionsLine("Usage: app -u http://yourURL");
                help.AddOptions(this);
                return help;

            }
        }
    }
}
